# coding=utf-8
# author:xc
# datetime:2018/8/27 16:06

from dbConnection.MysqlConn import Mysql
from flask import request
from app import util, upload_files
from . import html


# 课程详情
@html.route('/api/course/category', methods=['POST', 'GET'])
def api_course_category():
    try:
        cid = request.values.get('cid')
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql = "select * from girl_course_chapter where cid ='%s'and status=1 limit %d,%d " % (cid, num, util.PAGE_NUM)
        sql1 = "select count(*) from girl_course_chapter where cid='%s' and status=1" % cid
        sql2 = " select a.*,c.typeName,c.sid as subjectId,b.courseName as title ,b.tid as typeId from girl_course as" \
               " a left join girl_type as b on a.tid=b.tid left join" \
               " girl_subject as c on c.sid=b.sid where a.cid='%s' and a.status=1" % (cid)
        result = mysql.getAll(sql, None)
        data = mysql.getOne(sql2, None)
        count = mysql.getOne(sql1, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        res = []
        detail = {}
        if data:
            data_detail = dict()
            data_detail['cid'] = data['cid']
            data_detail['courseName'] = data['courseName']
            data_detail['title'] = data['title']
            data_detail['typeName'] = data['typeName']
            data_detail['sid'] = data['subjectId']
            data_detail['tid'] = data['typeId']
            if not data['cover'].startswith('http'):
                data_detail['cover'] = upload_files.baseUrl + data['cover']
            else:
                data_detail['cover'] = data['cover']
            data_detail['addTime'] = data['addTime'].strftime('%Y-%m-%d %H:%M:%S')
            data_detail['info'] = data['info']
            detail = data_detail
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                data = dict()
                data['chapterId'] = x['id']
                data['chapterName'] = x['chapterName']
                if not x['url'].startswith('http:'):
                    data['url'] = upload_files.baseUrl + x['url']
                else:
                    data['url'] = x['url']
                data['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data['flag'] = x['flag']
                res.append(data)
        if count:
            count = count['count(*)']
        else:
            count = 0
    except Exception as e:
        print e
        count = 0
        code = util.CODE_ERROR
        res = []
        detail = {}
    data = {
        'count': count,
        'code': code,
        'res': res,
        'detail': detail
    }
    return util.to_json(data)
